package org.achao.server;

import com.alibaba.fastjson.JSON;
import org.achao.beasn.dto.MessageDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static org.achao.redis.RedisMsgListenerContainer.PRIVATE_MSG;
import static org.achao.redis.RedisMsgListenerContainer.PUBLIC_MSG;

/**
 * @author achao
 * @description 结合redis订阅发布的 websocket服务器
 * @date 2023/10/2 15:38
 */
@Component
@ServerEndpoint("/redis/socket/{uuid}")
@SuppressWarnings(value = {"rawtypes"})
public class RedisWebSocketDemoServer {

    /**
     * 存储当前对象
     **/
    public static final Map<String, Session> sessionMap = new ConcurrentHashMap<>();


    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisUtil(RedisTemplate redisTemplate) {
        RedisWebSocketDemoServer.redisTemplate = redisTemplate;
    }

    /**
     * 创建websocket连接
     *
     * @param session
     * @param uuid
     */
    @OnOpen
    public void onOpen(@PathParam("uuid") String uuid, Session session) {
        System.out.println(uuid + "打开了websocket双向通道...");
        sessionMap.put(uuid, session);
    }

    /**
     * 关闭websocket连接
     *
     * @param uuid
     */
    @OnClose
    public void onClose(@PathParam("uuid") String uuid) {
        sessionMap.remove(uuid);
        System.out.println(uuid + "断开了websocket双向通道...");
    }

    /**
     * 异常断开websocket连接
     *
     * @param error
     */
    @OnError
    public void onError(@PathParam("uuid") String uuid,Throwable error) {
        sessionMap.remove(uuid);
        System.out.println("websocket异常断开连接...");
        error.printStackTrace();
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("服务器接受到的消息为【" + message + "】");
        MessageDto messageDto = JSON.parseObject(message, MessageDto.class);

        if (messageDto.getType() == 1) {
            // 私聊
            redisTemplate.convertAndSend(PRIVATE_MSG, message);
        }else {
            // 群聊
            redisTemplate.convertAndSend(PUBLIC_MSG, message);
        }
    }

    /**
     * 私聊
     *
     * @param message
     */
    public void privateMsg(String message) {
        MessageDto messageDto = JSON.parseObject(message, MessageDto.class);
        try {
            if (messageDto != null) {
                Session s1 = sessionMap.get(messageDto.getToId());
                Session s2 = sessionMap.get(messageDto.getFromId());
                s1.getBasicRemote().sendText(JSON.toJSONString(messageDto));
                s2.getBasicRemote().sendText(JSON.toJSONString(messageDto));
            }
        } catch (NullPointerException e) {
            System.out.println("要找的人不在我这...");
        } catch (IOException e) {
            System.err.println("发送异常");
            e.printStackTrace();
        }
    }

}
